/*
 * @Author: yangzonglong
 * @Date: 2021-05-11 15:26:13
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-11-29 17:01:22
 * @Auditor:
 */
import React, { useState, useEffect, useRef } from 'react';
import Qs from 'query-string';
import { Radio } from 'antd';
import { PageHeader, history, units, Button, db } from '@library';
import View from '../../../../components/fd/view/View';
import MobileView from '../../../../components/fd/mobileview/MobileView';
import PrintView from '../../../../components/fd/printview/PrintView';
import classNames from 'classnames';
import { ViewRefProps } from '../../../../components/fd/interface';
import { addOrUpdateByUrl } from '../../../../components/fd/components/dataList/api';
import style from './style.module.scss';
import { getForm } from './Api';

const Preview = () => {

  const query = Qs.parseUrl(window.location.href).query;

  const formRef = useRef<ViewRefProps>(null);
  const [formData, setFormData] = useState<any>({});
  const [platform, setPlatform] = useState<'pc' | 'mobile' | 'print'>('pc');
  const [state, setState] = useState({ list: [], formDesc: '', formName: '', modelListAndModelName: '', enviromentConfig: undefined });
  const [disabled, setDisabled] = useState(false);

  useEffect(() => {
    if (query.id)
      db.getForm(query.id as string).then((details) => {
        if (details) {
          setState({
            list: JSON.parse(details.content).list,
            modelListAndModelName: JSON.parse(details.content).modelListAndModelName,
            enviromentConfig: details.enviromentConfig ? JSON.parse(details.enviromentConfig) : undefined,
            formDesc: details.formDesc,
            formName: details.formName,
          });
        }
      });
  }, [query.id]);

  useEffect(() => {
    if (query.name) {
      const state: any = history.location.state || {};

      setFormData(state);
      formRef.current?.setFieldsValue(state);

      setDisabled(!!state.disabled);

      units.serverLoading('/bk/api/fd/Form/findOne', {
        where: {
          'formName': decodeURIComponent(query.name as string)
        }
      }).then(result => {
        setState(result.content ? {
          list: JSON.parse(result.content).list,
          modelListAndModelName: JSON.parse(result.content).modelListAndModelName,
          enviromentConfig: result.enviromentConfig ? JSON.parse(result.enviromentConfig) : undefined,
          formDesc: result.formDesc,
          formName: result.formName,
        } : { list: [], formDesc: '', formName: '', modelListAndModelName: '', enviromentConfig: undefined });

      });
    }
  }, [query.id, query.name]);

  const onAction = async () => {
    const data = await formRef.current?.validateFields();
    const res = await addOrUpdateByUrl(formData.url, { ...formData, ...data });
    if (res) {
      history.back();
    }
  };

  return (
    <>
      <PageHeader extra={formData?.showPageHeaderBtn && <Button onClick={onAction}> 提交 </Button>} />
      <div className={classNames('common-block', style.formDesign)} style={platform === 'mobile' ? { width: '375px' } : {}}>

        {query?.id && <div className={platform === 'mobile' ? style.previewBtn : style.previewBtnPc}>
          <Radio.Group onChange={(e) => {
            if (e.target.value === 'print') {
              window.open('/workflow/print?formId=' + query.id);
            } else {
              setPlatform(e.target.value || platform);
            }
          }} value={platform} style={{ margin: '4px' }}>
            <Radio.Button value="pc">PC端预览</Radio.Button>
            {/* <Radio.Button value="mobile">手机端预览</Radio.Button> */}
            <Radio.Button value="print">打印预览</Radio.Button>
            <Radio.Button onClick={async () => {
              const data = await formRef.current?.validateFields();
              console.log(data);
            }} value="">获取值</Radio.Button>
          </Radio.Group>
        </div>}
        {platform === 'pc' ? (
          <View
            formatFormBtns
            disabled={disabled}
            structure={state}
            ref={formRef}
            data={formData}
            formInfo={{ formDesc: state.formDesc, formName: state.formName }} />
        ) : platform === 'print' ? <PrintView structure={state} formInfo={{ formDesc: state.formDesc, formName: state.formName }} /> : (
          <MobileView
            structure={{ ...state, list: state?.list.map((item: any) => ({ ...item, options: { ...item.options, disabled: true } })) }}
            formInfo={{ formDesc: state.formDesc, formName: state.formName }}
          />
        )}
        {/* <View structure={state} formInfo={{ formDesc: state.formDesc, formName: state.formName }} /> */}
      </div>
    </>
  );
};

export default Preview;
